/*
 * Copyright (c) 2001-2018 GuaHao.com Corporation Limited. All rights reserved.
 * This software is the confidential and proprietary information of GuaHao Company.
 * ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with GuaHao.com.
 *
 */
package com.bolt.convention.data.code;


import com.bolt.convention.data.ResultMessage;
import com.bolt.convention.exception.ServiceException;
import com.bolt.convention.exception.ServiceValidException;

import java.util.List;

/**
 * 通用编码
 */
public enum CommonCode implements ServiceCode {


    // 通用响应码
    INVALID_ARGS("1", COMMON, "参数无效"),
    DATA_NOT_FOUND("2", COMMON, "当前数据不存在"),
    NO_LOGIN("3", COMMON, "用户未登录"),
    INVALID_AUTH("4", COMMON, "权限无效"),
    RECORD_EXISTED("5", COMMON, "已经存在该记录"),
    ILLEGAL_STATE("6", COMMON, "无效的状态"),
    /**
     * 用于http中，比如服务端未实现POST，但客户端对这个接口发起了POST请求后会报告此类错误
     */
    METHOD_NOT_ALLOWED("7", SYS, "不支持的请求方法"),

    INVALID_IO("8", SYS, "IO异常"),

    UNKNOWN_ERROR("9", SYS,"未知的系统错误"),
    // 各类异常响应码
    DB_ERROR("10", SYS, "数据库异常"),
    CACHE_ERROR("11", SYS, "缓存异常"),
    HTTP_ERROR("12", SYS, "调用HTTP接口发生异常"),
    RETURN_NULL_ERROR("13", SYS, "服务不能返回空对象");
    /**
     * 响应码
     */
    private final String code;

    /**
     * 响应消息
     */
    private final String message;

    /**
     * 构造函数
     *
     * @param code 响应码
     * @param codeSign 响应码标识
     * @param message 消息
     */
    CommonCode(String code, String codeSign, String message) {
        this.code = codeSign + "_" + code;
        this.message = message;
    }

    @Override
    public String code() {
        return code;
    }

    @Override
    public String message() {
        return message;
    }

    @Override
    public ServiceException failure() {
        if (this == INVALID_ARGS) {
            return new ServiceValidException(this);
        }
        return new ServiceException(this);
    }

    public ServiceValidException invalid(List<ResultMessage.ViolationItem> violationItems) {
        return new ServiceValidException(violationItems);
    }
}
